package com.pdweb.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pdweb.dao.EmpresasDao;
import com.pdweb.vo.Empresas;

/**
 * Servlet implementation class EmpresasConsultaServlet
 */
@WebServlet("/EmpresasConsultaServlet")
public class EmpresasConsultaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmpresasConsultaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}
	
	protected void doService(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		try {

			Empresas empresas = new Empresas();

			empresas.setNome(request.getParameter("nomeEmpresa"));
			

			EmpresasDao empresasDao = new EmpresasDao();
			
			String sql = null;
			List<Empresas> Empresas1 = null;
			
			String buscaNumeros = empresas.getNome();
			
			
			Pattern p = Pattern.compile("[0-9]{"+ empresas.getNome().length() +"}");   
			Matcher m = p.matcher(buscaNumeros);
			if (m.find()) {  
				if(empresas.getNome().length() == 14){
					sql = "select * from Empresas where ST_CNPJ_EMP = '"+empresas.getNome()+"';";
				} else {
					sql = "select * from Empresas where ID_EMPRESA_EMP = '"+empresas.getNome()+"';";
				}
			} else sql = "select * from Empresas where ST_NOME_EMP LIKE '%"+empresas.getNome()+"%';";
 			
			Empresas1 = empresasDao.consultaEmpresa(sql);			
			 
			 if( Empresas1 != null){
				 
				 request.setAttribute("empresasConsulta", Empresas1);
					
					getServletContext().getRequestDispatcher("/consulta_empresa.jsp").forward(request,response);
			 } else {
				 request.setAttribute("erro", "sem valores");
					
					getServletContext().getRequestDispatcher("/consulta_empresa.jsp").forward(request,response);
			 }
			
			
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
